import { isReferee } from "@/func";
import { Player } from "@minecraft/server";
import { ModalFormData } from "@minecraft/server-ui";
import { Game, GameComponent } from "@sapi-game/main";
import { DimensionIds, EntityTypeIds } from "@sapi-game/utils/vanila-data";
import { ScoreBoardDataBase } from "sapi-pro";
import { MonopolyBackState } from "../states/backState";

/**管理大富翁的配置项 */
export class MonopolyConfigSetter extends GameComponent<MonopolyBackState> {
    private readonly db = new ScoreBoardDataBase(
        "dfw_setting",
        "大富翁设置",
        false
    );

    override onAttach(): void {
        //设置按钮绑定
        this.subscribe(
            Game.events.buttonPush,
            (t) => {
                const p = t.source as Player;
                if (!isReferee(p)) return p.sendMessage("你无权配置此项目");
                this.showForm(p);
            },
            {
                loc: [-194, -35, 261],
                sourceType: EntityTypeIds.Player,
                dimensionId: DimensionIds.Overworld,
            }
        );
    }

    showForm(target: Player) {
        let form = new ModalFormData();
        form.title("大富翁配置");
        let keys = this.db.keys();
        for (const key of keys) {
            let score = this.db.get(key);
            if (!score) return;
            form = form.textField(key, "请输入", {
                defaultValue: score.toString(),
            });
        }

        form.show(target).then((result) => {
            const values = result.formValues;
            if (result.canceled || !values) return;
            try {
                for (let i = 0; i < keys.length; i++) {
                    const key = keys[i];
                    const value = values[i];

                    if (value == undefined || value === "") {
                        return target.sendMessage(`${key}不能为空`);
                    }
                    const parsed = Number(value);
                    if (Number.isNaN(parsed)) {
                        return target.sendMessage(`${key}必须是数字`);
                    }
                    this.db.set(key, parsed);
                }
                target.sendMessage("§a配置成功");
            } catch (err) {
                target.sendMessage("§c配置失败，错误:" + err);
            }
        });
    }
}
